const Article = require("../model/article.model");
const moment = require("moment");
const { selectById } = require("../service/category.service");
// 原始sql
const { QueryTypes, Op, literal } = require("sequelize");
const seq = require("../db/seq");
const { queryInfoServiceList } = require("../service/tag.service");
const { queryUserInfo } = require("../service/user.service");
const articleNews = require("../model/articleNews.model");
class ArticleService {
  // 查询列表
  async queryAllArticles(requestObj, page = 1, size = 10) {
    console.log(requestObj, "--queryall--articles--Service");
    let articles;
    let total;
    // 多参数查询
    if (JSON.stringify(requestObj) !== "{}" && requestObj) {
      const { title, tagId, typeId, status, collectIds, isBanner } = requestObj;
      const filterObj = {};
      if (title) {
        filterObj.title = {
          [Op.like]: `%${requestObj.title}%`,
        };
      }
      if (status) {
        filterObj.status = status;
      }
      if (isBanner) {
        filterObj.isBanner = isBanner;
      }
      if (tagId) {
        filterObj[Op.and] = [
          literal(`CONCAT(',', tagsId, ',') LIKE '%,${tagId},%'`),
        ];
        if (collectIds) {
          filterObj[Op.and].push(
            literal(`CONCAT(',', collectIds, ',') LIKE '%,${collectIds},%'`)
          );
        }
        console.log("filterobj", filterObj);
      } else if (collectIds) {
        console.log("filterobj", filterObj);
        filterObj[Op.and] = [
          literal(`CONCAT(',', collectIds, ',') LIKE '%,${collectIds},%'`),
        ];
      }
      if (typeId) {
        filterObj.typeId = typeId;
      }

      const offset = (page - 1) * size;
      total = await Article.count({
        where: filterObj,
      });
      console.log(filterObj, "banner");
      console.log(page, size, "@@@@@");
      articles = await Article.findAll({
        where: filterObj,
        offset,
        limit: size,
      });
    } else {
      const offset = (page - 1) * size;
      console.log(page, size, "@@@@@");
      articles = await Article.findAll({ offset, limit: size });
      total = await Article.count();
    }

    for (let i = 0; i < articles.length; i++) {
      if (!articles[i]["dataValues"].typeId) {
      } else {
        const cateInfo = await selectById(articles[i]["dataValues"].typeId);
        articles[i]["dataValues"].typeInfo = cateInfo;
      }
      if (!articles[i]["dataValues"].tagsId) {
      } else {
        const res = await queryInfoServiceList(
          articles[i]["dataValues"].tagsId
        );
        // console.log("res", res);
        articles[i]["dataValues"].tagList = res;
      }
      if (articles[i]["dataValues"].userId) {
        const id = articles[i]["dataValues"].userId;
        console.log("article------@@", id);
        const res = await seq.query("select * from `bl-user` where id=?", {
          replacements: [id],
          type: QueryTypes.SELECT,
        });
        console.log(res, "ddd");
        articles[i]["dataValues"].authorInfo = res && res[0];
      }
    }

    return { data: articles, total };
  }
  // 按id查询文章信息
  async queryArticleByIdService({ id }) {
    const res = await seq.query("select * from articles where id = ?", {
      replacements: [id],
      type: QueryTypes.SELECT,
    });
    console.log("res,", res);
    if (res && res[0] && res[0].tagsId) {
      const tagList = await queryInfoServiceList(res[0].tagsId);
      console.log(tagList, "tagList");
      res[0].tagList = tagList;
    }

    if (res[0].typeId != null) {
      const cateInfo = await selectById(res[0].typeId);
      res[0].typeSort = cateInfo;
      return res;
    } else {
      return res;
    }
  }

  async addService(params) {
    console.log(params, "params");
    const {
      title,
      summary,
      tagsId,
      typeId,
      isTop,
      status,
      composeType,
      link,
      isRecommend,
      isBanner,
      contentMd,
      userId,
      titleImg,
    } = params;
    const createTime = moment().valueOf();

    if (link) {
      const res = await seq.query(
        "insert into articles (title,summary,tagsId,typeId,isTop,status,composeType,link,isRecommend,isBanner,userId,createTime,titleImg,contentMd) values(:title,:summary,:tagsId,:typeId,:isTop,:status,:composeType,:link,:isRecommend,:isBanner,:userId,:createTime,:titleImg,:contentMd)",
        {
          replacements: {
            title,
            summary,
            tagsId,
            typeId,
            isTop,
            status,
            composeType,
            link,
            isRecommend,
            isBanner,
            userId,
            createTime,
            titleImg,
            contentMd,
          },
          type: QueryTypes.INSERT,
        }
      );
    } else {
      params.createTime = createTime;
      const res = await Article.create(params);
      console.log("----article----add", res);
      return res && res[0] ? res[0] : "";
    }
  }

  async modifyService(params) {
    const {
      id,
      title,
      summary,
      tagsId,
      typeId,
      isTop,
      status,
      composeType,
      isRecommend,
      isBanner,
      contentMd,
      dianzanIds,
    } = params;
    const updateTime = moment().valueOf();
    const modifyObj = {};
    Object.keys(params).forEach((item) => {
      if (item !== "id" && params[item] !== "") {
        modifyObj[item] = params[item];
      }
    });
    modifyObj.updateTime = updateTime;
    console.log(modifyObj, "modifyobj");
    const res = await Article.update(modifyObj, {
      where: {
        id,
      },
    });
    console.log("---article---modify----", res);
    return res && res[0] ? res[0] : "";
  }

  async deleteServiceById(id) {
    console.log(id, "id");
    await seq.query("delete from articles where id =:id", {
      replacements: { id },
      type: QueryTypes.DELETE,
    });
  }

  async deleteServiceByIds(ids) {
    await Article.destroy({
      where: {
        id: ids,
      },
    });
  }

  async queryByUserIdService(requestObj) {
    const res = await Article.findAll({ where: requestObj });
    // console.log(res,"回显res");
    return res;
  }

  async modifyServiceSocket(params) {
    const {
      id,
      title,
      summary,
      tagsId,
      typeId,
      isTop,
      status,
      composeType,
      isRecommend,
      isBanner,
      contentMd,
      dianzanIds,
      collectIds,
    } = params;
    const updateTime = moment().valueOf();
    const modifyObj = {};
    Object.keys(params).forEach((item) => {
      if (item !== "id") {
        modifyObj[item] = params[item];
      }
    });
    modifyObj.updateTime = updateTime;
    console.log(modifyObj, "modifyobj");
    const res = await Article.update(modifyObj, {
      where: {
        id,
      },
    });
    console.log("---article---modify----", res);
    return res && res[0] ? res[0] : "";
  }

  // 查询文章评论
  async commentByIdService(id) {
    id = parseInt(id);
    let requestObj = {
      forumId: id,
    };
    const res = await articleNews.findAll({
      where: requestObj,
    });
    console.log(res, "@@@@@qk");
    for (let i = 0; i < res.length; i++) {
      const id = res[i]["dataValues"].userId;
      const data = await seq.query("select * from `bl-user` where id=?", {
        replacements: [id],
        type: QueryTypes.SELECT,
      });
      res[i]["dataValues"].authorInfo = data && data[0];
    }
    return res;
  }

  // 添加评论
  async addNewsService(requestObj) {
    const res = articleNews.create(requestObj);
    return res;
  }
}

module.exports = new ArticleService();
